package org.jeecg.modules.wlhy.shiboetc;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.PdfUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.ecloud.sdk.util.DateUtil;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.shiboetc.service.resVo.InvoiceInfosVo;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Log4j2
@Service
public class ShiBoEtcService {


    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Autowired
    private IHyVehicleService vehicleService;

    @Value(value = "${ysb-daikai.baseUrl:}")
    private String localbaseUrl;

    @Autowired
    private RedisUtil redisUtil;

    @Value(value = "${shiboEtc.publicKey:}")
    private String publicKey;


    @Value(value = "${shiboEtc.privateKey:}")
    private String privateKey;


    /**
     * 初始化 获取getCompany3DESKey
     *
     * @throws UnsupportedEncodingException
     */
    public  String getCompany3DESKey() throws Exception {

        //获取世博etc参数

        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String baseUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");
        String idNum = HyCfgUtil.getCfgItem2("shibo_etc","idNum");

        String url = baseUrl+"/rms/invoice/getCompany3DESKey";


        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCertType("73");
        company3DESKey.setCompanyCode(companyCode);
        company3DESKey.setIdNum(idNum);
        String jsonStr = JSON.toJSONString(company3DESKey);

        String encrypt = RSAEncrypt.encrypt(jsonStr, publicKey);
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encrypt);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
        log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (!object.getString("code").equals("200")){
            throw new Exception(object.getString("message"));
        }
        String result = object.getString("message");
        log.info("数据为==="+result);

      //  String s = RSAEncrypt.decrypt(object.getString("message"),"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIT8fv5r98f4kIALthivJATDpl1E6F2iHrllP5Gi/MyuVqIYT+8/D15XEJN6McAQ7iSPdHIZRKDl9IpznpEuPfbiUlyR+dFcpTJ39pqNWL6a0ZA5toDhISKfheWsVkZigux/6LBghCfefyHcUC5Qh9LNZRB5f4riVnDEqUIOq5EjAgMBAAECgYB+A5j+0yY/Gh0rCG3r5AIYdaCuXr5lA1tjyDo9cZllBopXHPyZs0KH3a56YN7FpgVTJZBtEd6DLIPVsgt+fLf/W8+JIFkyt5FF93C+z8xsXJrj9fyKWNla73LbMqDjVh8UlxdmyeC+/mEomWPx6jScLfprUJjZdzMWX9eA//6QCQJBAMgXz3VplhkGq8JlYLLfgJuOjLYFE8lDeK4zPITgV/MJK7ClVSZk3wgK5FOtPt707rjf8CthlHyEzO8hs19/n08CQQCqJLL2kh+VcGQi9VGlKr2AEQ+wKZ1zVUP4P86GavqBbCWGfewv6cPXz0cXVAZRWPRNnJS6QMNI8JaE8V6g3FvtAkBx7wTlIUMjauYAYgNmttcfPFMpDckPcAjWgDw0mR3bOFyVT/8lRoispq8OanaDM8p+oJy7xutq359lhrYBacUHAkBllEmAalcO6i3urRXUjULb7dO28fF9xP8yfC26FK6AjGeO9ykGpgL1mluwMsse0APzPjORS08MAg9rSYuccFM1AkBAyGngBoe3ScYt5FIo+reoO8ECQbDyOf8qHbnMsqS+onrOlizQBZrcGQRFx7sQgPAzUOQQZoRflMt9KKTAjiXL");
          String s = RSAEncrypt.decrypt(object.getString("message"),privateKey);

        log.info("3des 秘钥为=="+s);
        if (redisUtil.get("shibo3des")!=null){
            redisUtil.del("shibo3des");
        }
        redisUtil.set("shibo3des",s,60*60*24);
        return s;
    }





    /**
     * 3DES 秘钥确认
     *
     * @throws UnsupportedEncodingException
     */
    public  Boolean doCompanyDesAck(String des) throws Exception {

        //获取世博etc参数

        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String baseUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = baseUrl+"/rms/invoice/doCompanyDesAck";


        log.info("秘钥:" + des);
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyCode(companyCode);
        company3DESKey.setDes(des);
        String jsonStr = JSON.toJSONString(company3DESKey);
        String encrypt = RSAEncrypt.encrypt(jsonStr, publicKey);
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encrypt);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
       // log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (!object.getString("code").equals("200")){
            throw new Exception(object.getString("message"));
        }
        String result = object.getString("message");
        log.info("数据为==="+result);

        return true;
    }


    /**
     * 车辆备案
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> vehicleFiling(HyVehicle vehicle, String ESKey) throws Exception {

        /*private String companyNum;// 企业编号 String 由财税平台生成并分配给用户。 否
        private String plateNum;// 车牌号 String 不超过 10 字符 是
        private Integer plateColor;// 车牌颜色 Integer 参考附录 4.2.1 是
        private String companyName;// 企业名称 String 企业名称 否
        private Integer serviceOperation;// 营运类型 Integer 参考附录 4.2.2 否*/

        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String baseUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = baseUrl+"/rms/invoice/vehicleFiling";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyNum(companyCode);
        company3DESKey.setPlateNum(vehicle.getVehicleNumber());
        company3DESKey.setPlateColor(1);
        company3DESKey.setServiceOperation(1);
        String jsonStr = JSON.toJSONString(company3DESKey);
        String encrypt = DesUtil.encode(jsonStr, ESKey);

        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encrypt);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
        //log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        JSONObject object = JSONObject.parseObject(post);
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }
        String result = object.getString("result");
        String encode1 = DesUtil.decode(result,ESKey);
        log.info("=="+encode1);
        log.info("请求返回:" + encode1);
        return Result.OK();
    }

    /**
     * 上传开始运单
     * @param hyShippingNote
     * @param vehicle
     * @return
     */
    public Result<?> waybillStart(HyShippingNote hyShippingNote, HyVehicle vehicle, String ESKey) {

        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        log.info("开始上传实时运单");
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = reqUrl+"/rms/invoice/waybillStart";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyNum(companyCode);
        company3DESKey.setPlateNum(vehicle.getVehicleNumber());
        company3DESKey.setPlateColor(convert(vehicle.getVehiclePlateColorCode()));
        company3DESKey.setNum(hyShippingNote.getShippingNoteNumber());
        company3DESKey.setServiceOperation(1);
       // company3DESKey.setStartTime(DateUtils.dateTimeToString(hyShippingNote.getStatusDtReceive()));
        company3DESKey.setStartTime(DateUtils.dateTimeToString(hyShippingNote.getStatusDtLoading()));
        company3DESKey.setDestAddr(hyShippingNote.getSendAddress());
        company3DESKey.setSourceAddr(hyShippingNote.getReceiveAddress());
        company3DESKey.setPredictEndTime(DateUtils.dateTimeToString(hyShippingNote.getStatusDtUnloading()));
        company3DESKey.setFee(hyShippingNote.getDriverFee().multiply(new BigDecimal("100")));//司机总运费
        company3DESKey.setTitleType("1");
        String fileUrl = localbaseUrl + "/sys/common/static/" + encode(hyShippingNote.getShippingContract(),"utf-8");
        try {
            String s = PdfUtil.encodeImageToBase64(fileUrl);
            company3DESKey.setBase64Str(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(fileUrl);
        company3DESKey.setWaybillFileName(file.getName());
        company3DESKey.setContractType("1");


        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
        log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        String result = object.getString("result");
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }

        String encode1 = null;
        try {
            encode1 = DesUtil.decode(result, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("=="+encode1);
        log.info("请求返回明文:" + encode1);

        return Result.OK();
    }

    /**
     * 上传原始运单
     * @param
     * @throws Exception
     */
    public Result<?> originWaybillEnd(HyShippingNote shippingNote, HyVehicle vehicle, HyDriver driver,String ESKey){

        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = reqUrl+"/rms/invoice/originWaybillEnd";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyNum(companyCode);
        company3DESKey.setNum(shippingNote.getShippingNoteNumber());
        company3DESKey.setPlateNum(vehicle.getVehicleNumber());
        //转换车牌颜色码
        int code = convert(vehicle.getVehiclePlateColorCode());
        company3DESKey.setPlateColor(code);
        company3DESKey.setLoadTime(DateUtils.dateTimeToString(shippingNote.getStatusDtLoading()));
        company3DESKey.setLoadAddr(shippingNote.getSendAddress());
        company3DESKey.setUnloadTime(DateUtils.dateTimeToString(shippingNote.getStatusDtUnloading()));
        company3DESKey.setUnloadAddr(shippingNote.getReceiveAddress());
        company3DESKey.setFee(shippingNote.getDriverFee().multiply(new BigDecimal("100")));
        company3DESKey.setShipper(shippingNote.getReceiveContactName());
        company3DESKey.setCarrier(driver.getDriverName());
        String fileUrl = localbaseUrl + "/sys/common/static/" + encode(shippingNote.getShippingContract(),"utf-8");

        try {
            String s = PdfUtil.encodeImageToBase64(fileUrl);
            log.info("合同地址为"+s);
            company3DESKey.setBase64Str(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(fileUrl);
        company3DESKey.setWaybillFileName(file.getName());
        company3DESKey.setContractType("2");

        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
       // log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }

        return Result.OK();
    }

    private int convert(@NotEmpty(message = "车牌颜色不允许为空") String vehiclePlateColorCode) {
        if (vehiclePlateColorCode.equals("1")) {
            return 0;
        } else if (vehiclePlateColorCode.equals("3")) {
            return 2;
        } else if (vehiclePlateColorCode.equals("4")) {
            return 3;
        } else if (vehiclePlateColorCode.equals("5") || vehiclePlateColorCode.equals("6") || vehiclePlateColorCode.equals("7") || vehiclePlateColorCode.equals("10")) {
            return 9;
        } else if (vehiclePlateColorCode.equals("8")) {
            return 5;
        } else if (vehiclePlateColorCode.equals("9")) {
            return 4;
        } else if (vehiclePlateColorCode.equals("2")) {
            return 1;
        }
        return 1;
    }
    /**
     * 上传结束运单
     */
    public Result<?> waybillEnd(HyShippingNote shippingNote,String ESKey){
        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");
        String companyId = HyCfgUtil.getCfgItem2("shibo_etc","companyId");


        //请求参数
        String url = reqUrl+"/rms/invoice/waybillEnd";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyNum(companyCode);
        company3DESKey.setCompanyId(companyId);
        company3DESKey.setNum(shippingNote.getShippingNoteNumber());
        company3DESKey.setRealDestAddr(shippingNote.getReceiveAddress());
        company3DESKey.setEndTime(DateUtils.dateTimeToString(shippingNote.getStatusDtUnloading()));

        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
       // log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }
        return Result.OK();
    }
    /**
     * 获取发票数据
     */
    public Result<?> invoiceInfos(String shippingNoteNumber, Date clearDate,String ESKey){

        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");



        String url = reqUrl+"/rms/invoice/invoiceInfos";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setWaybillNum(shippingNoteNumber);
        company3DESKey.setCompanyNum(companyCode);
        company3DESKey.setClearDate(DateUtil.getStringDate(clearDate));

        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
        e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
      //  log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        String result = object.getString("result");
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }
        String encode1 = null;
        InvoiceInfosVo infosVo = new InvoiceInfosVo();
        try {
            encode1 = DesUtil.decode(result, ESKey);
            log.info("=="+encode1);
            JSONObject jsonObject = JSONObject.parseObject(encode1);

            infosVo.setInvoiceNum(jsonObject.getString("invoiceNum"));
            infosVo.setInvoiceCode(jsonObject.getString("invoiceCode"));
            infosVo.setInvoiceMakeTime(jsonObject.getString("invoiceMakeTime"));
            infosVo.setInvoiceUrl(jsonObject.getString("invoiceUrl"));
            infosVo.setInvoiceHtmlUrl(jsonObject.getString("invoiceHtmlUrl"));
            infosVo.setEnStation(jsonObject.getString("enStation"));
            infosVo.setExStation(jsonObject.getString("exStation"));
            infosVo.setExTime(jsonObject.getString("exTime"));
            infosVo.setFee(jsonObject.getBigDecimal("fee"));
            infosVo.setTotalAmount(jsonObject.getBigDecimal("totalTaxAmount"));
            infosVo.setPlateNum(jsonObject.getString("plateNum"));
            infosVo.setVehicleType(jsonObject.getInteger("vehicleType"));
            infosVo.setSellerName(jsonObject.getString("sellerName"));
            infosVo.setSellerTaxpayerCode(jsonObject.getString("sellerTaxpayerCode"));
            infosVo.setWaybillNum(jsonObject.getString("waybillNum"));
            infosVo.setWaybillStartTime(jsonObject.getString("waybillStartTime"));
            infosVo.setWaybillEndTime(jsonObject.getString("waybillEndTime"));
            infosVo.setTotalAmount(jsonObject.getBigDecimal("totalAmount"));
            infosVo.setTaxRate(jsonObject.getBigDecimal("taxRate"));
            infosVo.setInvoiceType(jsonObject.getString("invoiceType"));
            infosVo.setAmount(jsonObject.getBigDecimal("amount"));
            infosVo.setTransactionId(jsonObject.getString("transactionId"));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.OK(infosVo);

    }
    /**
     * 查看运单状态
     */
    public Result<?> wayBillStatus(HyShippingNote shippingNote,String ESKey){

        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = reqUrl+"/rms/invoice/wayBillStatus";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setWaybillNum(shippingNote.getShippingNoteNumber());
        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
      //  log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }
        String result = object.getString("result");
        String encode1 = null;

        try {
            encode1 = DesUtil.decode(result, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("请求返回明文:" + encode1);

        return Result.OK(encode1);
    }


    /**
     * 撤销运单
     *
     */
    public Result<?> cancelWaybill(HyShippingNote shippingNote,String ESKey){

        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");


        String url = reqUrl+"/rms/invoice/cancelWaybill";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setWaybillNum(shippingNote.getShippingNoteNumber());
        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
      //  log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (object.getString("code").equals("500")){
            return Result.error(object.getString("message"));
        }

        return Result.OK();
    }
    /**
     * 历史运单上传
     */
    public Result<?> waybillHistoryStart(HyVehicle vehicle,HyShippingNote shippingNote,String ESKey){

        //请求参数
        if(!HyCfgUtil.isUsed("shibo_etc")){
            throw new JeecgBootException("世博etc服务暂未开启,请联系管理员。");
        }
        log.info("开始上传历史运单");
        String reqUrl = HyCfgUtil.getCfgItem2("shibo_etc","url");
        String companyCode = HyCfgUtil.getCfgItem2("shibo_etc","companyCode");
        String companyId = HyCfgUtil.getCfgItem2("shibo_etc","companyId");

        //请求参数
        String url = reqUrl+"/rms/invoice/waybillHistoryStart";
        Company3DESKey company3DESKey = new Company3DESKey();
        company3DESKey.setCompanyNum(companyCode);
        //company3DESKey.setCompanyId(companyId);
        company3DESKey.setNum(shippingNote.getShippingNoteNumber());
        company3DESKey.setPlateNum(vehicle.getVehicleNumber());
        company3DESKey.setPlateColor(convert(vehicle.getVehiclePlateColorCode()));
        company3DESKey.setServiceOperation(1);
        company3DESKey.setStartTime(DateUtils.dateTimeToString(shippingNote.getStatusDtLoading()));
        company3DESKey.setSourceAddr(shippingNote.getSendAddress());
        company3DESKey.setDestAddr(shippingNote.getReceiveAddress());
        company3DESKey.setPredictEndTime(DateUtils.dateTimeToString(shippingNote.getStatusDtUnloading()));
        company3DESKey.setFee(shippingNote.getDriverFee().multiply(new BigDecimal("100")));
        company3DESKey.setTitleType("1");
        company3DESKey.setWaybillEndTime(DateUtils.dateTimeToString(shippingNote.getStatusDtUnloading()));
        String fileUrl = null;
        if (StringUtils.isNotEmpty(shippingNote.getShippingContract())){
             fileUrl = localbaseUrl + "/sys/common/static/" + encode(shippingNote.getShippingContract(),"utf-8");
            try {
                String s = PdfUtil.encodeImageToBase64(fileUrl);
                log.info("合同文件base流为===="+s);
                company3DESKey.setBase64Str(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            return Result.error("合同地址为空，请签署合同");
        }


        File file = new File(fileUrl);
        company3DESKey.setWaybillFileName(file.getName());
        company3DESKey.setContractType("1");
        String jsonStr = JSON.toJSONString(company3DESKey);
        String encode = null;
        try {
            encode = DesUtil.encode(jsonStr, ESKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqVo reqVo = new reqVo();
        reqVo.setCompanyCode(companyCode);
        reqVo.setContent(encode);
        String jsonStr2 = JSON.toJSONString(reqVo);
        log.info("请求参数url:" + url);
        log.info("请求参数:" + jsonStr2);
        String post = HttpUtil.post(url, jsonStr2);
        log.info("请求返回:" + post);
        JSONObject object = JSONObject.parseObject(post);
        if (!object.getString("code").equals("200")){
            return Result.error(object.getString("message"));
        }
        return Result.OK();
    }



    /**
     * 图片转义
     */
    private String encode(String url, String chartSet) {

        {
            try {
                Matcher matcher = Pattern.compile("[^\\x00-\\xff]").matcher(url);//双字节,包括中文和中文符号[^\x00-\xff]  中文[\u4e00-\u9fa5]
                while (matcher.find()) {
                    String tmp = matcher.group();
                    url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, chartSet));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("双字节编码异常：", e);
            }
            return url;
        }
    }


}




